package top.wkq.middleware.dynamic.thread.pool.sdk.trigger.listener;

import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.wkq.middleware.dynamic.thread.pool.sdk.domain.DynamicThreadPoolService;
import top.wkq.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import top.wkq.middleware.dynamic.thread.pool.sdk.registry.IRegistry;

import java.util.List;


/**
 * <h1>动态线程池变更监听</h1>
 */

public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {
    private Logger logger = LoggerFactory.getLogger(ThreadPoolConfigAdjustListener.class);

    private final DynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry iRegistry; // 变更完，立马上报

    public ThreadPoolConfigAdjustListener(DynamicThreadPoolService dynamicThreadPoolService, IRegistry iRegistry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.iRegistry = iRegistry;
    }

    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity threadPoolConfigEntity) {
        logger.info("动态线程池，调整线程池配置。线程池名称：{}  核心线程数：{} 最大线程数：{}", threadPoolConfigEntity.getThreadPoolName(), threadPoolConfigEntity.getCorePoolSize(), threadPoolConfigEntity.getMaximumPoolSize());
        dynamicThreadPoolService.updateThreadPoolConfig(threadPoolConfigEntity);
        // 更新后上报最新数据
        List<ThreadPoolConfigEntity> threadPoolConfigList = dynamicThreadPoolService.getThreadPoolConfigList();
        iRegistry.reportThreadPool(threadPoolConfigList);
        ThreadPoolConfigEntity threadPoolConfig = dynamicThreadPoolService.getThreadPoolConfigByName(threadPoolConfigEntity.getThreadPoolName());
        iRegistry.reportThreadPoolParameter(threadPoolConfig);
    }
}
